package com.cg.big_event.interceptor;

import com.cg.big_event.utils.JwtUtil;
import com.cg.big_event.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
//拦截器 拦截token，对没有登录令牌的的操作拒绝访问
@Component
public class LoginInterecptor implements HandlerInterceptor {
   @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //获取请求头中的token
        String token = request.getHeader("Authorization");
          try{
              //判断redis中是否有token，将token作为key， value为token
              ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue ();
              //获取redis中的token
              String redistoken = stringStringValueOperations.get(token);
              //判断是否过期
              if (redistoken==null)
              {
                  throw new RuntimeException("token过期");
              }
              //解析token
                Map<String, Object> claims = JwtUtil.parseToken(token);
                //将用户信息保存到ThreadLocal中
                ThreadLocalUtil.set(claims);
                //放行
                return true;
            }catch(Exception e)
            {
                //不放行
                response.setStatus(401);
                return false;
         }
            }
            @Override
         public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束，删除ThreadLocal中的用户信息
        ThreadLocalUtil.remove();
    }
}
